package com.dongnan.hl7v2;

import ca.uhn.hl7v2.HL7Exception;
import ca.uhn.hl7v2.model.*;
import ca.uhn.hl7v2.protocol.ReceivingApplication;
import ca.uhn.hl7v2.protocol.ReceivingApplicationException;
import ca.uhn.hl7v2.util.Terser;

import java.io.IOException;
import java.util.*;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class LilianReceivingApplication implements ReceivingApplication {

    private DataBaseCconnectPool dataBaseCconnectPool = DataBaseCconnectPool.getInstance();
    private  MyParaMap myParaMap = MyParaMap.getInstance();
    private  MyMessageProcessor myMessageProcessor = new MyMessageProcessor();


    @Override
    public Message processMessage(Message message, Map<String, Object> map) throws ReceivingApplicationException, HL7Exception {
        myParaMap.cleanResult();
        Terser terser = new Terser(message);
        String messageType = terser.get("/.MSH-9-1" )+"_"+terser.get("/.MSH-9-2" );
        String messageID = terser.get("/.MSH-10");
        String rawMessage = map.get("raw-message").toString();
        String sendingIP = map.get("SENDING_IP").toString();
        String sendingPort = map.get("SENDING_PORT").toString();
        String processSuccessFlag = "true";
        String processInfo = "处理成功";
        myMessageProcessor.processorMessage(messageType,message,myParaMap);
        try {
            myParaMap.getSQLList(messageType);
        } catch (Exception e) {
            processSuccessFlag = "false";
            processInfo = e.toString();
        }
        String rawMessageSql  = "INSERT INTO `raw_hl7_message`(`messageType`, `messageID`, `SendIP`, `SendPort`,`rawMessage`,`processSuccessFlag`,`processInfo`)\n" +
                " VALUES ('"+messageType+"', '"+messageID+"', '"+sendingIP+"', '"+sendingPort+"','"+rawMessage+"',"+processSuccessFlag+",'"+processInfo+"');";
        Message message1 = null;
        try {
            Connection conn = dataBaseCconnectPool.getConnection();
            Statement st = conn.createStatement();
            st.execute(rawMessageSql);
            for (String string :myParaMap.sqlList){
//                System.out.println(string);
                st.execute(string);
            }
            message1 = message.generateACK();
            conn.close();
            st.close();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return message1;
    }

    @Override
    public boolean canProcess(Message message) {
        return true;
    }
}